# -*- coding: utf-8 -*-

'''
2017-6-3 pylint format
'''

import os
import hashlib

# ----------------------------------------------------------------------------
# Use For read file!
# ----------------------------------------------------------------------------


def getfile_md5(filepath):
    '''获取文件md5'''
    m5val = hashlib.md5()
    data = file(filepath, "rb")
    while True:
        readval = data.read(1024)
        if not readval:
            break
        m5val.update(readval)
    data.close()
    return m5val.hexdigest()


def read_jsonfile(filename, mod="r+"):
    '''读取json文件'''
    import json
    fopen = file(filename, mod)
    ret = json.loads(fopen.read().decode("utf-8"))
    fopen.close()
    return ret


def read_plistfile(filename):
    '''读取plist文件'''
    import plistlib
    fplist = plistlib.readPlist(filename)
    return fplist


def read_andxml(xmlfile, valuestring):
    '''读取xml文件'''
    from xml.etree import ElementTree
    root = ElementTree.parse(xmlfile)
    list_children = root.getiterator("resources")
    for node in list_children:
        if node.tag == "resources":
            for item in node:
                if item.tag == "string":
                    item.text = valuestring


def read_zipfile(zippath, tarpath=os.path.join(os.getcwd())):
    '''读取zip文件 解压到制定文件夹'''
    import zipfile
    import shutil

    if not os.path.isdir(tarpath):
        os.mkdir(tarpath)

    unzipobj = zipfile.ZipFile(zippath, 'r')
    for filename in unzipobj.namelist():
        filepath = os.path.join(tarpath, filename)
        filepath = filepath.replace("/", '\\')

        # path
        if filepath.endswith("\\"):
            filepath = filepath[:-1]
            if os.path.isdir(filepath):
                shutil.rmtree(filepath)
            os.mkdir(filepath)
        # file
        else:
            path_file = os.path.split(filepath)[0]
            if not os.path.isdir(path_file):
                os.mkdir(path_file)
            data = unzipobj.read(filename)
            fileobj = open(filepath, "w+")
            fileobj.write(data)
            fileobj.close()
    unzipobj.close()
